package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicCompanyTestDO;
import com.cssy.xxkj.basic.entity.BasicCurrencyTestDO;
import com.cssy.xxkj.basic.entity.BasicModePaymentTestDO;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicPayDO;
import com.cssy.xxkj.logic.entity.LogicPayItemDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareItemDO;
import com.cssy.xxkj.logic.service.ILogicPayService;
import com.cssy.xxkj.logic.service.ILogicPurchaseService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareItemService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareService;
import com.cssy.xxkj.logic.service.ILogicUtilService;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;

/**
 * 
 * 付款controller
 * @author zeyong.gui
 * 
 */
@Controller
@RequestMapping("/logic/paymoney")
public class PayMoneyController extends BaseController<LogicPayDO>{
	private static final Logger logger = Logger.getLogger(PayMoneyController.class);
	private static final String MANAGER = "/xxkj/logic/paymoney/PayMoneyManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/paymoney/PayMoneyOperation";// 添加、修改、显示页面
	
	@Resource(name="logicPayService")
    private ILogicPayService  logicPayService;

	@Resource(name = "logicPurchaseService")
	private ILogicPurchaseService logicPurchaseService;
	
	@Resource(name = "logicPurchaseWareService")
	private ILogicPurchaseWareService logicPurchaseWareService;
	
	@Resource(name = "logicPurchaseWareItemService")
	private ILogicPurchaseWareItemService logicPurchaseWareItemService;
	
	@Resource(name = "basicUtilService")
	private IBasicUtilService basicUtilService;
	
	@Resource(name = "logicUtilService")
	private ILogicUtilService logicUtilService;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions payScs = new SearchConditions();
		hander.getWheres(payScs);
		//供应商Id
		String supeId = request.getParameter("supeId");
		if(StringUtils.isNotBlank(supeId)){
			payScs.addCondition("zd009SupeId", supeId, SearchCondition.OP_EQUAL);
		}
		//单据状态
		String zdStatus = request.getParameter("zdStatus");
		if(StringUtils.isNotBlank(zdStatus)){
			payScs.addCondition("zd003Status", zdStatus, SearchCondition.OP_EQUAL);
		}
		payScs.setOrderBy("bizCreatorDate desc");
		SearchResult result= logicPayService.findListByExample(payScs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
		
	}
	
	@Override
	public String operationForm(HttpServletRequest request, @PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if (OperationFlag.ADD.equals(flag)) {
			// 新增单据时操作
			model.addAttribute("flag", "ADD");
			//查询采购入库单
			SearchConditions whScs = new SearchConditions();
			whScs.setRemovedProperty(null);
			List<LogicPurchaseWareDO> pcsList = logicUtilService.resultPurchaseWare(whScs);
			model.addAttribute("pcsList", pcsList);
			//查询付款方式
			SearchConditions payScs = new SearchConditions();
			payScs.setRemovedProperty(null);
			List<BasicModePaymentTestDO> payments = basicUtilService.resultPayments(payScs);
			model.addAttribute("paysList", payments);
			//供应商id
			model.addAttribute("superId", id);
		} else {
			//修改单据时操作
			LogicPayDO lpd = logicPayService.findListById(id);
			model.addAttribute("pay", lpd);
		}
		return EIDT;
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicPayDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		String flagMark = request.getParameter("flagMark");
		if(StringUtils.isBlank(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("付款单内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			curAP.setZd003Status(flagMark);
			if(BillStatusUtil.PAY_BILL_STATUS_ONE.equals(flagMark)){
				//保存草稿
				logicPayService.paySave(curAP, request);
			}
			if(BillStatusUtil.PAY_BILL_STATUS_TWO.equals(flagMark)){
				//保存草稿
				logicPayService.payCommit(curAP, request);
			}
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
	try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				if(StringUtils.isBlank(field)){
					continue;
				}else{
					logicPayService.deleteBizRemoved(field);
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 供应商列表
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setLimitPage(false);//不分页
		scs.setRemovedProperty(null);
		hander.getWheresNotLimit(scs);
		List<BasicCompanyTestDO> list =basicUtilService.resultCompany(scs);
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(list));
	}
	
	/**
	 * 查询付款item集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/girdItems")
	public void girdItems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String payId = request.getParameter("payId");
		if(StringUtils.isNotBlank(payId)){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("payId", payId);
			List<LogicPayItemDO> payItemList = logicPayService.findItemListByMap(paramMap);
			OutJsonGrid out = new OutJsonGrid(payItemList);
			out.printJSon(response);
		}
	}
	
	/**
	 * 根据采购入库单id查询单据信息
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/pcswQuary")
	@ResponseBody
	public LogicPayDO pcswQuary(HttpServletRequest request,Model model) throws Exception{
		LogicPayDO payMoney = new LogicPayDO();
		BigDecimal pcswSum = BigDecimal.ZERO;
		try{
			//采购订单ID
			String pcsId = request.getParameter("pcsId");
			LogicPurchaseDO pcs = logicPurchaseService.findListById(pcsId);
			if(pcs !=null ){
				payMoney.setZd010ExRateVal(pcs.getZd004Exchange());
				SearchConditions curScs = new SearchConditions();
				curScs.setRemovedProperty(null);
				curScs.addCondition("id", pcs.getZd003CurrencyId(), SearchCondition.OP_EQUAL);
				List<BasicCurrencyTestDO> curList = basicUtilService.resultCurrency(curScs);
				if(curList==null||curList.isEmpty()||curList.size()==0){
					payMoney.setZd010ExRateCode("");
					payMoney.setZd010ExRateName("");
				}else{
					payMoney.setZd010ExRateCode(curList.get(0).getZd002CurrencyCode());
					payMoney.setZd010ExRateName(curList.get(0).getZd001CurrencyName());
				}
			}
			//采购入库单ID,根据采购入库单查询item集合
			String pcswId = request.getParameter("pcswId");
			LogicPurchaseWareDO pcsw = logicPurchaseWareService.findListById(pcswId);
			if(pcsw !=null){
				payMoney.setZd009SupeId(pcsw.getZd008SupeId());
				payMoney.setZd009SupeCode(pcsw.getZd008SupeCode());
				payMoney.setZd009SupeName(pcsw.getZd008SupeName());
			}
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("pcswId", pcswId);
			List<LogicPurchaseWareItemDO> pcswItemList = logicPurchaseWareItemService.findListByMap(paramMap);
			for(LogicPurchaseWareItemDO pcswItem : pcswItemList){
				if(pcswItem==null){
					continue;
				}
				BigDecimal taxprice = pcswItem.getZd016Price()==null?BigDecimal.ZERO:pcswItem.getZd016Price();
				BigDecimal zdQuantity = pcswItem.getZd018HsQuantity()==null?BigDecimal.ZERO:pcswItem.getZd018HsQuantity();
				pcswSum = pcswSum.add(taxprice.multiply(zdQuantity));
			}
			//赋值应收总金额
			payMoney.setZd004SumAmount(pcswSum);
			//已付款金额
			paramMap.put("zdStatus", BillStatusUtil.PAY_BILL_STATUS_TWO);
			BigDecimal lastSumMoney = logicPayService.findQueryHasPayMoney(paramMap);
			payMoney.setZd005HasAmount(lastSumMoney==null?BigDecimal.ZERO:lastSumMoney);
		}catch(Exception e){
			e.printStackTrace();
		}
		return payMoney;
	}
	
	/**
	 * 根据采购入库单的id查询采购入库单item集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/pcswItemQuery")
	public void pcswItemQuery(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String pcswId = request.getParameter("pcswId");
		if(StringUtils.isNotBlank(pcswId)){
			//查询采购入库单的item
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("pcswId", pcswId);
			List<LogicPurchaseWareItemDO> pcswItemList = logicPurchaseWareItemService.findListByMap(paramMap);
			if(pcswItemList==null){
				pcswItemList = new ArrayList<LogicPurchaseWareItemDO>();
			}
			Map<String, Object> payItemMap = new HashMap<String, Object>();
			payItemMap.put("pcswId", pcswId);
			payItemMap.put("zdStatus", BillStatusUtil.PAY_BILL_STATUS_TWO);
			Map<String, BigDecimal> payHasMap = logicPayService.findHasPayItemListByMap(payItemMap); 
			List<LogicPayItemDO> payItemList = this.payItemListComp(pcswItemList, payHasMap);
			OutJsonGrid out = new OutJsonGrid(payItemList);
			out.printJSon(response);
		}
	}
	
	/**
	 * 组装付款单的item集合列表
	 * @param pcswItemList
	 * @param payHisList
	 * @return
	 */
	private List<LogicPayItemDO> payItemListComp(List<LogicPurchaseWareItemDO> pcswItemList, Map<String, BigDecimal> payHasMap){
		List<LogicPayItemDO> payItemList = new ArrayList<LogicPayItemDO>();
		for(LogicPurchaseWareItemDO pcswItem : pcswItemList){
			if(pcswItem==null){
				continue;
			}
			String keyStr = pcswItem.getZd003MaterId()+"_"+pcswItem.getZd007Model()+"_"
					+pcswItem.getZd011Size()+"_"+pcswItem.getZd009Color()+"_"
					+pcswItem.getZd010Quality();
			LogicPayItemDO payItem = new LogicPayItemDO();
			payItem.setZd002MaterId(pcswItem.getZd003MaterId());
			payItem.setZd003MaterCode(pcswItem.getZd004Code());
			payItem.setZd004MaterName(pcswItem.getZd005Name());
			payItem.setZd005Type(pcswItem.getZd005Type());
			payItem.setZd006Spec(pcswItem.getZd006Spec());
			payItem.setZd007Model(pcswItem.getZd007Model());
			payItem.setZd009Color(pcswItem.getZd009Color());
			payItem.setZd010Quality(pcswItem.getZd010Quality());
			payItem.setZd011Size(pcswItem.getZd011Size());
			payItem.setZd012Unit(pcswItem.getZd012Unit());
			payItem.setZd013TaxPrice(pcswItem.getZd017TaxPrice());
			//单价
			BigDecimal price = pcswItem.getZd016Price()==null?BigDecimal.ZERO:pcswItem.getZd016Price();
			payItem.setZd013Price(price);
			//入库数量
			BigDecimal zdQuantity = pcswItem.getZd018HsQuantity()==null?BigDecimal.ZERO:pcswItem.getZd018HsQuantity();
			payItem.setZd020Quantity(zdQuantity);
			//赋值应付总金额
			BigDecimal zdSumMoney = price.multiply(zdQuantity);
			payItem.setZd016Amount(zdSumMoney);
			if(payHasMap==null || payHasMap.get(keyStr)==null){
				//没有历史的付款记录
				payItem.setZd019NoMoney(zdSumMoney);
				payItem.setZd017HasMoney(BigDecimal.ZERO);
				payItem.setZd018TheMoney(zdSumMoney);
			}else{
				//存在历史的付款记录
				payItem.setZd019NoMoney(zdSumMoney.subtract(payHasMap.get(keyStr)));
				payItem.setZd017HasMoney(payHasMap.get(keyStr));
				payItem.setZd018TheMoney(zdSumMoney.subtract(payHasMap.get(keyStr)));
			}
			payItemList.add(payItem);
		}
		return payItemList;
	}
	
}
 